package com.hutiao.snowhb.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hutiao.snowhb.dao.BaseDao;

@Component
public class ChatService {

	@Autowired
	private BaseDao baseDao;
	
	
	public Map<String, Object> getAutoResponse(String text) {
		
		// 首先取出所有一级关键字
		String sql = "select key1 from snowmm_chat group by key1;";
		
		List<Map<String, Object>> tempList = this.baseDao.queryForList(sql);
		if (tempList == null || tempList.size() == 0) {
			return null;
		}
		
		List<String> key1List = new ArrayList<String>();
		
		for (Map<String, Object> temp : tempList) {
			
			String key1 = temp.get("key1").toString();
			
			if (key1.indexOf("&") == -1) {
				if (text.indexOf(key1) != -1) {
					key1List.add(key1);
				}
			} else {
				String key1_0 = key1.split("&")[0];
				String key1_1 = key1.split("&")[1];
				if (text.indexOf(key1_0)!=-1 && text.indexOf(key1_1)!=-1) {
					key1List.add(key1);
				}
			}
		}
		
		if (key1List.size() == 0) {
			return null;
		}
		
		// 随机取一个key1
		int i = new java.util.Random().nextInt(key1List.size());
		String key1 = key1List.get(i);
		
		sql = "select key2 from snowmm_chat where key1='"+key1+"' group by key2;";
		tempList = this.baseDao.queryForList(sql);
		
		List<String> key2List = new ArrayList<String>();
		boolean hasEmptykey2 = false;
		
		if (tempList != null && tempList.size() > 0) {
			
			for (Map<String, Object> temp : tempList) {
				String key2 = temp.get("key2").toString();
				if (key2.equals("")) {
					hasEmptykey2 = true;
					continue;
				}
				
				String[] kklist = key2.split("\\|");
				for (String k : kklist) {
					if (text.indexOf(k) != -1) {
						key2List.add(key2);
						continue;
					}
				}
			}
			
		}
		
		if (key2List.size() == 0 && !hasEmptykey2) {
			return null;
		}
		
		String key2 = "";
		if (key2List.size() > 0) {
			// 随机取一个key2
			key2 = key2List.get(new java.util.Random().nextInt(key2List.size()));
		}
		
		sql = "select type,response from snowmm_chat where key1='"+key1+"' and key2='"+key2+"';";
		tempList = this.baseDao.queryForList(sql);
		
		if (tempList == null || tempList.size() == 0) {
			return null;
		}
		
		if (tempList.size() == 1) {
			return tempList.get(0);
		}
		
		int j = new java.util.Random().nextInt(tempList.size());
		return tempList.get(j);
	}
	
}
